﻿using System;
using System.Collections;
using System.Collections.Generic;

using UnityEngine;

namespace ALPackage
{
    /// <summary>
    /// UI系统层级管理多个对象的挂载脚本基类
    /// </summary>
    /// <typeparam name="T">层级管理数据类型</typeparam>
    public abstract class _AALUILayerBasicNodeListMono<T> : MonoBehaviour where T : _AALUILayerBasicMonoData
    {
        [SerializeField]
        public List<T> nodes = new List<T>();
        //是否需要检测
        protected bool _m_bNeedCheck = false;
        //当前记录的状态
        protected bool _m_bDealedEnableState = false;

        //有效和无效的时候分别注册和注销显示对象
        private void OnEnable()
        {
            _m_bNeedCheck = true;

            //到管理对象中进行处理
            ALCommonTaskController.CommonActionAddNextFrameTask(_check);
        }

        private void OnDisable()
        {
            _m_bNeedCheck = true;

            //到管理对象中进行处理
            ALCommonTaskController.CommonActionAddNextFrameTask(_check);
        }

        private void OnDestroy()
        {
            _m_bNeedCheck = true;
            //直接检测
            _check();
            if (nodes != null)
            {
                foreach (var node in nodes)
                {
                    node.discard();
                }
            }
        }

        /// <summary>
        /// 检测函数
        /// </summary>
        protected virtual void _check()
        {
            if(!_m_bNeedCheck || null == this || null == gameObject)
            {
#if UNITY_EDITOR
                if(_m_bNeedCheck)
                    UnityEngine.Debug.LogError("Check mono Enable error!");
#endif
                return;
            }

            _m_bNeedCheck = false;

            //判断状态是否变更，如未变更则不处理
            if(_m_bDealedEnableState == gameObject.activeInHierarchy)
                return;
            //设置新状态
            _m_bDealedEnableState = gameObject.activeInHierarchy;

            if(_m_bDealedEnableState)
            {
                if (nodes != null)
                {
                    foreach (var node in nodes)
                    {
                        //对象有效，此时进行注册处理
                        ALUILayerMgr.instance.addUILayerNode(node.createUILayerNode());
                    }
                }
            }
            else
            {
                if (nodes != null)
                {
                    foreach (var node in nodes)
                    {
                        //此时执行注销操作
                        ALUILayerMgr.instance.rmvLayerNode(node.goInstanceId);
                    }
                }
            }
        }
    }
}
